package com.stgy.lease.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * ClassName:JacksonConfig
 * Package:com.stgy.lease.common.config
 * Description:
 *
 * @Author:helei
 * @Create:2024/8/31 - 11:34
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();

        // Create and register custom module
        SimpleModule module = new SimpleModule();

        // Serialize Long as String
        module.addSerializer(Long.class, ToStringSerializer.instance);

        // Custom deserializer for Long that handles empty strings
        module.addDeserializer(Long.class, new StdDeserializer<Long>(Long.class) {
            @Override
            public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                String value = p.getText();
                if (value == null || value.isEmpty()) {
                    return null; // Convert empty strings to null
                }
                try {
                    return Long.parseLong(value);
                } catch (NumberFormatException e) {
                    throw new IOException("Invalid Long value: " + value, e);
                }
            }
        });

        mapper.registerModule(module);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Ignore unknown properties

        return mapper;
    }
}
